﻿using SqlsugarService.Application.IService.Plan;
using SqlsugarService.Domain.Materials;
using SqlsugarService.Infrastructure.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using SqlsugarService.Application.Until;
using SqlsugarService.Application.DTOs.PlanDto;

namespace SqlsugarService.Application.Service.Plan
{
    /// <summary>
    /// 产品服务
    /// </summary>
    public class ProductEntityService : IProductEntityService
    {
        private readonly IBaseRepository<ProductEntity> _productRepository;
        private readonly IMapper _mapper;

        public ProductEntityService(
            IBaseRepository<ProductEntity> productRepository,
            IMapper mapper)
        {
            _productRepository = productRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取产品分页列表
        /// </summary>
        public async Task<ApiResult<PageResult<List<GetProductDto>>>> GetProductList(GetProductSearchDto search)
        {
            var query =await _productRepository.GetAllAsync();
            
            if (!string.IsNullOrEmpty(search.MaterialNumber))
            {
                query = query.Where(x => x.MaterialNumber==search.MaterialNumber || x.MaterialName==search.MaterialNumber).ToList();
            }
            if (!string.IsNullOrEmpty(search.MaterialNumber))
            {
                query = query.Where(x => x.SpecificationModel == search.SpecificationModel).ToList();
            }
            if (!string.IsNullOrEmpty(search.Unit))
            {
                query = query.Where(x => x.Unit == search.Unit).ToList();
            }

            var totalCount = query.Count();
            var totalPage = (int)Math.Ceiling(totalCount * 1.0 / search.PageSize);

            var products =query
                .OrderBy(x => x.Id)
                .Skip((search.PageIndex - 1) * search.PageSize)
                .Take(search.PageSize)
                .ToList();

            var result = _mapper.Map<List<GetProductDto>>(products);

            return ApiResult<PageResult<List<GetProductDto>>>.Success(
                new PageResult<List<GetProductDto>>
                {
                    TotalCount = totalCount,
                    TotalPage = totalPage,
                    Data = result
                },
                ResultCode.Success);
        }

        /// <summary>
        /// 新增产品
        /// </summary>
        public async Task<ApiResult> AddProduct(InsertupdateproductentityDto dto)
        {
            // 验证数据有效性
            if (string.IsNullOrEmpty(dto.MaterialName))
            {
                return ApiResult.Fail("产品名称不能为空", ResultCode.Error);
            }

            dto.Id = Guid.NewGuid();
            dto.MaterialNumber = GenerateProductNumberByTime();
            var product = _mapper.Map<InsertupdateproductentityDto, ProductEntity>(dto);

            var result = await _productRepository.InsertAsync(product);

            return ApiResult.Success(ResultCode.Success);
        }
        /// <summary>
        /// 根据当前时间生成唯一的 ProductNumber，格式为 D + yyyyMMddHHmmss
        /// </summary>
        /// <returns></returns>
        private string GenerateProductNumberByTime()
        {
            var now = DateTime.Now;
            var timePart = now.ToString("yyyyMMddHHmmssfff");
            return $"CP{timePart}";
        }
        /// <summary>
        /// 更新产品信息
        /// </summary>
        public async Task<ApiResult> UpdateProduct(InsertupdateproductentityDto dto)
        {
            var product = await _productRepository.GetByIdAsync(dto.Id);
            if (product == null)
            {
                return ApiResult.Fail("产品不存在", ResultCode.NotFound);
            }

            _mapper.Map(dto, product);

            var result = await _productRepository.UpdateAsync(product);

            return ApiResult.Success( ResultCode.Success);
        }

        /// <summary>
        /// 删除产品
        /// </summary>
        public async Task<ApiResult> DeleteProduct(Guid id)
        {
            var result = await _productRepository.SoftDeleteAsync(id);

            return ApiResult.Success( ResultCode.Success);
        }

    }
}